// 引入多语言支持模块
import { changeLanguage, initLanguage, getCurrentText } from './language.js';
import { initTheme, toggleTheme } from './theme.js';

// 等待DOM完全加载
document.addEventListener('DOMContentLoaded', function() {
    // 初始化语言设置
    initLanguage();
    
    // 初始化主题设置
    initTheme();
    
    // 添加主题切换按钮事件监听器
    const themeToggleButton = document.getElementById('themeToggle');
    if (themeToggleButton) {
        themeToggleButton.addEventListener('click', toggleTheme);
    }
    
    // 添加语言切换按钮事件监听器
    document.querySelectorAll('.language-selector button').forEach(button => {
        button.addEventListener('click', function() {
            changeLanguage(this.dataset.lang);
            // 更新按钮状态
            document.querySelectorAll('.language-selector button').forEach(btn => {
                btn.classList.remove('active');
            });
            this.classList.add('active');
        });
    });
    
    // 粒子特效初始化
    function initParticles() {
        const particlesContainer = document.getElementById('particles');
        if (!particlesContainer) return;
        
        const particleCount = 60; // 减少粒子数量以便更好地显示连线
        const particles = [];
        
        for (let i = 0; i < particleCount; i++) {
            const particle = createParticle(particlesContainer);
            particles.push(particle);
        }
        
        // 创建连线容器
        const linesContainer = document.createElement('div');
        linesContainer.className = 'lines-container';
        linesContainer.style.position = 'absolute';
        linesContainer.style.top = '0';
        linesContainer.style.left = '0';
        linesContainer.style.width = '100%';
        linesContainer.style.height = '100%';
        linesContainer.style.pointerEvents = 'none';
        linesContainer.style.zIndex = '1';
        particlesContainer.appendChild(linesContainer);
        
        // 开始连线动画
        animateLines(particles, linesContainer);
    }
    
    function createParticle(container) {
        const particle = document.createElement('div');
        particle.className = 'particle';
        
        // 随机大小 - 增加大小范围
        const size = Math.random() * 8 + 3;
        particle.style.width = size + 'px';
        particle.style.height = size + 'px';
        
        // 随机位置
        const x = Math.random() * 100;
        const y = Math.random() * 100;
        particle.style.left = x + '%';
        particle.style.top = y + '%';
        
        // 随机动画延迟
        particle.style.animationDelay = Math.random() * 8 + 's';
        particle.style.animationDuration = (Math.random() * 4 + 6) + 's';
        
        // 随机透明度变化
        const opacity = Math.random() * 0.4 + 0.4;
        particle.style.opacity = opacity;
        
        // 随机动画名称 - 创建不同的动画效果
        const animations = ['float', 'float2', 'float3', 'float4'];
        const randomAnimation = animations[Math.floor(Math.random() * animations.length)];
        particle.style.animationName = randomAnimation;
        
        // 存储粒子位置信息
        particle.x = x;
        particle.y = y;
        particle.baseX = x;
        particle.baseY = y;
        
        container.appendChild(particle);
        return particle;
    }
    
    function animateLines(particles, container) {
        function update() {
            // 清除现有连线
            container.innerHTML = '';
            
            // 计算粒子间距离并绘制连线
            for (let i = 0; i < particles.length; i++) {
                for (let j = i + 1; j < particles.length; j++) {
                    const p1 = particles[i];
                    const p2 = particles[j];
                    
                    // 获取粒子当前位置
                    const rect1 = p1.getBoundingClientRect();
                    const rect2 = p2.getBoundingClientRect();
                    const containerRect = container.getBoundingClientRect();
                    
                    const x1 = rect1.left + rect1.width / 2 - containerRect.left;
                    const y1 = rect1.top + rect1.height / 2 - containerRect.top;
                    const x2 = rect2.left + rect2.width / 2 - containerRect.left;
                    const y2 = rect2.top + rect2.height / 2 - containerRect.top;
                    
                    // 计算距离
                    const distance = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
                    
                    // 如果距离小于150px，绘制连线
                    if (distance < 150) {
                        const line = document.createElement('div');
                        line.className = 'particle-line';
                        
                        // 计算连线的长度和角度
                        const length = distance;
                        const angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
                        
                        // 设置连线样式
                        line.style.width = length + 'px';
                        line.style.left = x1 + 'px';
                        line.style.top = y1 + 'px';
                        line.style.transform = `rotate(${angle}deg)`;
                        
                        // 根据距离调整透明度
                        const opacity = (1 - distance / 150) * 0.3;
                        line.style.opacity = opacity;
                        
                        container.appendChild(line);
                    }
                }
            }
            
            requestAnimationFrame(update);
        }
        
        update();
    }
    
    // 创建额外的动画变体
    const style = document.createElement('style');
    style.textContent = `
        @keyframes float2 {
            0%, 100% {
                transform: translateY(0px) rotate(0deg) scale(1);
                opacity: 0.6;
            }
            50% {
                transform: translateY(-40px) rotate(180deg) scale(1.2);
                opacity: 1;
            }
        }
        
        @keyframes float3 {
            0%, 100% {
                transform: translateX(0px) translateY(0px) rotate(0deg);
                opacity: 0.7;
            }
            25% {
                transform: translateX(20px) translateY(-20px) rotate(90deg);
                opacity: 1;
            }
            50% {
                transform: translateX(0px) translateY(-40px) rotate(180deg);
                opacity: 0.8;
            }
            75% {
                transform: translateX(-20px) translateY(-20px) rotate(270deg);
                opacity: 1;
            }
        }
        
        @keyframes float4 {
            0%, 100% {
                transform: translateY(0px) rotate(0deg) scale(0.8);
                opacity: 0.5;
            }
            33% {
                transform: translateY(-30px) rotate(120deg) scale(1.1);
                opacity: 0.9;
            }
            66% {
                transform: translateY(-60px) rotate(240deg) scale(0.9);
                opacity: 0.7;
            }
        }
    `;
    document.head.appendChild(style);
    
    // 初始化粒子特效
    initParticles();
    
    // 平滑滚动到锚点
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });

    // 导航栏滚动效果
    window.addEventListener('scroll', function() {
        const header = document.querySelector('header');
        if (window.scrollY > 100) {
            header.style.background = 'rgba(255, 255, 255, 0.95)';
            header.style.backdropFilter = 'blur(10px)';
        } else {
            header.style.background = '#fff';
            header.style.backdropFilter = 'none';
        }
    });

    // CTA按钮点击事件
    const ctaButton = document.querySelector('.cta-button');
    if (ctaButton) {
        ctaButton.addEventListener('click', function() {
            const aboutSection = document.querySelector('#about');
            if (aboutSection) {
                aboutSection.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    }

    // 联系表单处理
    const contactForm = document.getElementById('contactForm');
    if (contactForm) {
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const formData = new FormData(contactForm);
            const name = contactForm.querySelector('input[type="text"]').value;
            const email = contactForm.querySelector('input[type="email"]').value;
            const message = contactForm.querySelector('textarea').value;
            
            // 简单的表单验证
            if (!name || !email || !message) {
                showNotification('请填写所有必填字段', 'error');
                return;
            }
            
            // 邮箱格式验证
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                showNotification('请输入有效的邮箱地址', 'error');
                return;
            }
            
            // 模拟表单提交
            showNotification('消息发送成功！我会尽快回复您。', 'success');
            contactForm.reset();
        });
    }

    // 通知函数
    function showNotification(message, type) {
        // 如果消息是模板消息，使用翻译文本
        if (message.includes('查看项目:')) {
            const projectName = message.replace('查看项目: ', '').replace('View project: ', '');
            message = getCurrentText('notification.view-project') + projectName;
        } else if (message.includes('即将跳转到')) {
            const platform = message.replace('即将跳转到', '').replace('Redirecting to ', '');
            message = getCurrentText('notification.redirect') + platform;
        } else if (message === '消息发送成功！我会尽快回复您。') {
            message = getCurrentText('form.success');
        } else if (message === '请填写所有必填字段') {
            message = getCurrentText('form.error.required');
        } else if (message === '请输入有效的邮箱地址') {
            message = getCurrentText('form.error.email');
        }
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.textContent = message;
        
        // 添加样式
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 5px;
            color: white;
            font-weight: 500;
            z-index: 10000;
            opacity: 0;
            transform: translateX(100%);
            transition: all 0.3s ease;
            max-width: 300px;
            word-wrap: break-word;
        `;
        
        // 根据类型设置背景色
        if (type === 'success') {
            notification.style.background = '#27ae60';
        } else if (type === 'error') {
            notification.style.background = '#e74c3c';
        } else {
            notification.style.background = '#3498db';
        }
        
        // 添加到页面
        document.body.appendChild(notification);
        
        // 显示动画
        setTimeout(() => {
            notification.style.opacity = '1';
            notification.style.transform = 'translateX(0)';
        }, 100);
        
        // 自动隐藏
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 3000);
    }

    // 作品集项目点击事件
    const portfolioItems = document.querySelectorAll('.portfolio-item');
    portfolioItems.forEach(item => {
        item.addEventListener('click', function() {
            const projectTitle = this.querySelector('h3').textContent;
            showNotification(`查看项目: ${projectTitle}`, 'info');
        });
    });

    // 技能标签动画
    const skillItems = document.querySelectorAll('.skill-item');
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const skillObserver = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.animation = 'fadeInUp 0.6s ease forwards';
            }
        });
    }, observerOptions);

    skillItems.forEach(item => {
        item.style.opacity = '0';
        skillObserver.observe(item);
    });

    // 滚动显示动画
    const animateElements = document.querySelectorAll('.about-content, .portfolio-grid, .contact-content');
    const elementObserver = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.animation = 'fadeInUp 0.8s ease forwards';
            }
        });
    }, observerOptions);

    animateElements.forEach(element => {
        element.style.opacity = '0';
        elementObserver.observe(element);
    });

    // 社交链接点击事件
    const socialLinks = document.querySelectorAll('.social-links a');
    socialLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const platform = this.textContent;
            showNotification(`即将跳转到${platform}`, 'info');
        });
    });

    // 页面加载完成后的欢迎动画
    window.addEventListener('load', function() {
        const heroContent = document.querySelector('.hero-content');
        if (heroContent) {
            heroContent.style.opacity = '0';
            heroContent.style.transform = 'translateY(30px)';
            
            setTimeout(() => {
                heroContent.style.transition = 'all 1s ease';
                heroContent.style.opacity = '1';
                heroContent.style.transform = 'translateY(0)';
            }, 100);
        }
    });

    // 响应式菜单处理（移动端）
    function handleResponsiveMenu() {
        const navLinks = document.querySelector('.nav-links');
        const windowWidth = window.innerWidth;
        
        if (windowWidth <= 768) {
            // 移动端菜单逻辑可以在这里添加
            // 例如：汉堡菜单按钮
        } else {
            // 桌面端正常显示
            if (navLinks) {
                navLinks.style.display = 'flex';
            }
        }
    }

    // 初始化响应式处理
    handleResponsiveMenu();
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResponsiveMenu);

    // 添加键盘导航支持
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            // ESC键可以用来关闭弹窗或菜单
            console.log('ESC键被按下');
        }
    });

    // 性能优化：使用requestAnimationFrame进行滚动事件处理
    let ticking = false;
    function updateHeaderOnScroll() {
        const header = document.querySelector('header');
        if (window.scrollY > 100) {
            header.style.background = 'rgba(255, 255, 255, 0.95)';
            header.style.backdropFilter = 'blur(10px)';
        } else {
            header.style.background = '#fff';
            header.style.backdropFilter = 'none';
        }
        ticking = false;
    }

    window.addEventListener('scroll', function() {
        if (!ticking) {
            requestAnimationFrame(updateHeaderOnScroll);
            ticking = true;
        }
    });
});
